package rocket

import (
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/jsonx"
	"time"
	"xialou_platform/app/errorx"
)

type (
	ProducerClient interface {
		Push(v interface{}) error
	}

	DelayProducerClient interface {
		Push(v interface{}, deliverTime time.Time) error
	}

	//封装的生产者客户端
	producerClient struct {
		pusher pusher
	}

	delayProducerClient struct {
		pusher delayPusher
	}
)

func NewProducerClient(pusher pusher) ProducerClient {
	return &producerClient{
		pusher: pusher,
	}
}
func (p *producerClient) Push(v interface{}) error {

	// marshal
	body, err := jsonx.Marshal(v)
	if err != nil {
		return errors.Wrapf(errorx.NewDefaultError("rocket task marshal error "), "【pushRqMsgErrorMarshal】tag : %s , v : %+v", p.pusher.Tag, v)
	}

	if err := p.pusher.Push(string(body)); err != nil {
		return errors.Wrapf(errorx.NewDefaultError("rocket mqs push message error"), " 【pushRqMsgError】 tag : %s , v : %v", p.pusher.Tag, v)
	}

	return nil
}

func NewDelayProducerClient(pusher delayPusher) DelayProducerClient {
	return &delayProducerClient{
		pusher: pusher,
	}
}

func (p *delayProducerClient) Push(v interface{}, deliverTime time.Time) error {
	// marshal
	body, err := jsonx.Marshal(v)
	if err != nil {
		return errors.Wrapf(errorx.NewDefaultError("rocket task marshal error "), "【pushRqMsgErrorMarshal】tag : %s , v : %+v", p.pusher.Tag, v)
	}

	if err := p.pusher.Push(string(body), deliverTime); err != nil {
		return errors.Wrapf(errorx.NewDefaultError("rocket mqs push delay message error"), " 【pushRqMsgError】 tag : %s , v : %v", p.pusher.Tag, v)
	}
	return nil
}
